package cn.zcy.service.impl;

import cn.zcy.dao.AccountDao;
import cn.zcy.domain.Account;
import cn.zcy.service.AccountService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

//    @Autowired
//    private TransactionManager transactionManager;

    @Override
    public void save(Account account) {
        accountDao.save(account);
    }

    @Override
    public void update(Account account) {
        accountDao.update(account);
    }

    @Override
    public void delete(Integer id) {

    }

    /**
     * 转账业务
     *
     * @param sourceName
     * @param targeName
     * @param money
     */
    @Transactional(rollbackFor = ArithmeticException.class)
    @Override
    public Integer transfer(String sourceName, String targeName, Double money) {

        //1.根据名称查询转出账户
        Account sourceAccount = accountDao.findByName(sourceName);
        //2.根据名称查询转入账户
        Account tagerAccount = accountDao.findByName(targeName);
        //3.转出账户减钱
        sourceAccount.setMoney(sourceAccount.getMoney() - money);
        //4.转入账户加钱
        tagerAccount.setMoney(tagerAccount.getMoney() + money);
        //5.更新转出账户
        System.out.println("哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈 = ");
//            int b=1/0;
        //6.更新转入账户
        accountDao.update(tagerAccount);

        ((AccountService)AopContext.currentProxy()).outMoney(sourceAccount);
        return 99;
    }

    @Transactional
    @Override
    public void outMoney(Account sourceAccount) {
        accountDao.update(sourceAccount);
    }

    @Override
    public Account findAccountById(Integer id) {
        return accountDao.findAccountById(id);
    }

    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }
}
